// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "VmiThread.h"
#include "unistd.h"
#include "Log/logging.h"
/*lint -save -e1401 */
VmiThread::VmiThread() : mTid(0)
{
    mStatus = VMI_THREAD_STATUS_NEW;
}
/*lint -restore */
VmiThread::~VmiThread()
{
    mStatus = VMI_THREAD_STATUS_EXIT;
}

// 获取执行方法的指针
void *ThreadProxyFunc(void* args)
{
    if (args == nullptr) {
        ERR(" invalid parameter");
        return nullptr;
    }
    auto newThread = static_cast<VmiThread *>(args);

    newThread->Run();

    return args;
}

// 开始执行线程
bool VmiThread::Start()
{
    mStatus = VMI_THREAD_STATUS_RUNNING;
    if (pthread_create(&mTid, nullptr, ThreadProxyFunc, this)) {
        mStatus = VMI_THREAD_STATUS_EXIT;
        mTid = 0;
        return false;
    }
    return true;
}

// 获取线程ID
pthread_t VmiThread::GetThreadID()
{
    return mTid;
}

// 获取线程状态
int VmiThread::GetState()
{
    return mStatus;
}

// 等待线程直至退出
void VmiThread::Join()
{
    if (pthread_join(mTid, nullptr) != 0){
        ERR(" pthread_join failed");
    }
}

// 等待线程退出或者超时
void VmiThread::Join(unsigned long mSec)
{
    if (mTid == 0) {
        return;
    }

    if (mSec == 0) {
        Join();
    } else {
        unsigned long k = 0;
        while (mStatus != VMI_THREAD_STATUS_EXIT && k < mSec) {
            (void)usleep(THREAD_JOIN_SLEEP_TIME_MS);
            k++;
        }
    }
}

void VmiThread::Stop()
{
    mStatus = VMI_THREAD_STATUS_EXIT;
}
